/**   
 * @Title: CashController.java 
 * @Package com.leesche.zcsp.node.web.controller.wechat.cash.cash 
 * @Description:() 
 * @author dennies yang
 * @date 2016年10月20日 下午3:05:58 
 * @version V1.0   
 */
package com.leesche.zcsp.node.web.controller.wechat.income.cash;

import com.leesche.zcsp.node.pay.wecha.data.Message;
import com.leesche.zcsp.node.pay.wecha.service.WechatService;
import com.leesche.zcsp.node.pay.wecha.utils.SignUtil;
import com.leesche.zcsp.node.utils.TenpayUtil;
import com.leesche.zcsp.node.utils.security.QEncodeUtil;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.constants.Constants;
import com.leesche.zcsp.node.web.model.SysUser;
import com.leesche.zcsp.node.web.model.SysUserCashDetail;
import com.leesche.zcsp.node.web.service.SysUserBalanceService;
import com.leesche.zcsp.node.web.service.SysUserCashDetailService;
import com.leesche.zcsp.node.web.service.SysUserService;
import com.leesche.zcsp.node.web.service.impl.data.read.QuerySysUserBalanceCondition;
import com.leesche.zcsp.node.web.service.impl.data.read.QuerySysUserCashDetailCondition;
import com.leesche.zcsp.node.web.service.impl.data.read.SysUserBalanceDto;
import com.leesche.zcsp.node.web.service.impl.data.writ.UpdateUserBalanceCommand;
import com.leesche.zcsp.node.web.service.privilege.PrivilegeService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Map;

/**
 * @Title: CashController.java
 * @Package com.leesche.zcsp.node.web.controller.wechat.cash.cash
 * @Description:()
 * @author dennies yang
 * @date 2016年10月20日 下午3:05:58
 * @version V1.0
 */
@Controller
@RequestMapping(value = "/wechat/income/cash")
public class CashController {
	private static final Logger logger = Logger.getLogger(CashController.class);
	@Autowired
	PrivilegeService privilegeService;

	@Autowired
	SysUserBalanceService sysUserBalanceService;

	@Autowired
	SysUserCashDetailService SysUserCashDetailService;

	@Autowired
	SysUserService sysUserService;

	@Autowired
	WechatService wechatService;
	
	private final static String SHOWVIEW = "wechat/income/cash/mainView";
	private final static String CASHLIST = "wechat/income/cash/cashList";

	/***
	 * 
	 * @Title: listView @Description: TODO(打开取现界面) @param @param model @param @return @return
	 *         String @throws
	 */
	@RequestMapping(value = "showView", method = RequestMethod.GET)
	public String showView(ModelMap model) {
		QuerySysUserBalanceCondition querySysUserBalanceCondition = new QuerySysUserBalanceCondition();
		querySysUserBalanceCondition.setUserId(privilegeService
				.getCurrentPrincipal().getUserid());
		model.put("balances", sysUserBalanceService
				.findByCondition(querySysUserBalanceCondition));
		return SHOWVIEW;
	}

	/***
	 * 
	 * @Title: listView @Description: TODO(打开取现列表界面) @param @param model @param @return @return
	 *         String @throws
	 */
	@RequestMapping(value = "list", method = RequestMethod.GET)
	public String list(Integer page, Integer rows, Model model) {
		// 增加用户取现列表 显示最近50条
		QuerySysUserCashDetailCondition querySysUserCashDetailCondition = new QuerySysUserCashDetailCondition();
		querySysUserCashDetailCondition.setPage(page);
		querySysUserCashDetailCondition.setRows(rows);
		querySysUserCashDetailCondition.setUserId(privilegeService
				.getCurrentPrincipal().getUserid());
		model.addAttribute("balances", SysUserCashDetailService
				.findAllByPage(querySysUserCashDetailCondition));
		return CASHLIST;
	}

	/***
	 * 
	 * @Title: lost
	 * @Description: TODO(取现以元为单位)
	 * @param @param password <交易密码>
	 * @param @param totalmoney<总金额 以分为单位>
	 * @param @param request
	 * @param @param response
	 * @param @param session
	 * @param @return
	 * @return Map<String,Object>
	 * @throws
	 */
	@ResponseBody
	@RequestMapping(value = "lost", method = RequestMethod.POST)
	public Map<String, Object> lost(String password, int totalmoney,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) {

		// 获取用户信息
		SysUser sysUser = sysUserService.selectByPrimaryKey(privilegeService
				.getCurrentPrincipal().getUserid());
		if (sysUser == null) {
			return WebResult.failure("提现失败!").toMap();
		}
		// 税率计算
		/*
		 * double charge=totalmoney*0.0006; int smoney=(int) ((charge*100)/100);
		 * if(charge>smoney){ smoney=smoney+1; }
		 * 
		 * int gmoney=totalmoney-smoney;
		 */

		/*
		 * if(totalmoney!=(smoney+gmoney)){ return
		 * WebResult.failure("体现失败!").toMap(); }
		 */

		try {

			System.out.println(password);
			System.out.println(sysUser.getPassword());
			System.out.println(QEncodeUtil.md5Encrypt(password));
			// 验证密码是否正确
			if (!sysUser.getPassword().equals(QEncodeUtil.md5Encrypt(password))) {
				return WebResult.failure("交易密码不正确").toMap();
			}
			// 获取用户当前的额度
			QuerySysUserBalanceCondition querySysUserBalanceCondition = new QuerySysUserBalanceCondition();
			querySysUserBalanceCondition.setUserId(privilegeService
					.getCurrentPrincipal().getUserid());
			SysUserBalanceDto userBalance = sysUserBalanceService
					.findByCondition(querySysUserBalanceCondition);
			// 验证体现额度
			if (userBalance.getCurrentmoney() < totalmoney) {
				return WebResult.failure("额度不够不能提现").toMap();
			}
			// 执行提现操作
			String ip = "";
			if (request.getHeader("x-forwarded-for") == null) {
				ip = request.getRemoteAddr();
			} else {
				ip = request.getHeader("x-forwarded-for");
			}

			String orderNo = SignUtil.getOrderNo();

			SysUserCashDetail sysUserCashDetail = new SysUserCashDetail();
			sysUserCashDetail.setLosttype(Long
					.valueOf(Constants.CASH_LOSTTYPE_WECHAT));
			sysUserCashDetail.setLostmoney(Long.valueOf(totalmoney));
			sysUserCashDetail.setLoststatus(Constants.CASH_LOSTSTATUS_FAILTURE);
			sysUserCashDetail.setReceivetime(new Date());
			sysUserCashDetail.setRemark(orderNo);
			sysUserCashDetail.setUpdatetime(new Date());
			sysUserCashDetail.setUserid(privilegeService.getCurrentPrincipal()
					.getUserid());

			// 插入提现明细表
			if (SysUserCashDetailService.insert(sysUserCashDetail) <= 0) {
				return WebResult.failure("提现失败!").toMap();
			}

			// 取现操作
			Message<String> result = wechatService
					.wechattransfers(ip, sysUser.getOpenid(), totalmoney,
							"用户取现",
							TenpayUtil.getCharacterEncoding(request, response),
							orderNo);
			if (Message.isSuccess(result.getType())) {// 取现成功
				// 更新用户账单表 当前额度 currentMoney -totalmoney 已取money lostMoney
				// (已去金额)+ totalmoney 税率 金额 othermoney +smoney;
				UpdateUserBalanceCommand ubCommand = new UpdateUserBalanceCommand();
				ubCommand.setTotalMoney(Long.valueOf(totalmoney));
				ubCommand.setgMoney(Long.valueOf(totalmoney));
				ubCommand.setSmoney(Long.valueOf(0));
				ubCommand.setUserId(privilegeService.getCurrentPrincipal()
						.getUserid());
				if (sysUserBalanceService.editSysUserByUserid(ubCommand) > 0) {
					// 更新提现明细表
					sysUserCashDetail
							.setLoststatus(Constants.CASH_LOSTSTATUS_SUCCESS);
					SysUserCashDetailService
							.updateByPrimaryKey(sysUserCashDetail);
				}

				return WebResult.success().info("取现成功").toMap();
			} else {
				return WebResult.failure(result.getContent()).toMap();
			}

		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			return WebResult.failure(e).toMap();
		}

	}

}
